/**
 * 消息者相关功能
 */
import { mysql } from 'src-ssr/db/connect';
import TableHelper from 'src-ssr/db/tableHelper';
import * as tools from 'src-ssr/util/common';
import logs from 'src-ssr/util/logs';
import { Sequelize, Op, QueryTypes } from 'sequelize';
import models, { sequelize } from 'src-ssr/db/sequelize';
import moment from 'moment';
import shortid from 'shortid';
import md5 from 'md5';

import * as singleUtils from 'src-ssr/controller/common/singleOperate';

import listConfig from 'app/search/manager/consumer/list.js';
import summaryConfig from 'app/search/manager/consumer/summary.js';

const menuName = 'consumer';
const modelName = 'm_consumers';
const modelLabel = '消费者信息';

// 列表
export const list = async (req, res) => {
  const { startRow, count, filter, sortBy, descending } = req.body;

  const where = await tools.assemblyWhere({
    filter,
    searchConfig: listConfig.search,
    fn: ({ where, field, search }) => {
    }
  });

  const exclude = ['uid', 'password', 'salt'];
  // 只取单条数据
  if (filter && filter.id) {
    where.id = filter.id;
    // exclude.splice(exclude.indexOf('history'), 1);
  }

  const order = sortBy ? [[sortBy, descending ? 'DESC' : 'ASC']] : [];

  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);
  // const right = await tools.checkUserRight(user, menuName, ['data']);
  // if (!right.data) { // 是否有查看全部的权限
  //   where.create_user_id = user.id;
  // }

  let ret = { rows: [], count: 0 };
  try {
    ret = await models[modelName].findAndCountAll({
      attributes: {
        exclude,
        include: [[Sequelize.literal(`IFNULL((
        SELECT SUM(d.money)
        FROM t_sale_details d
        LEFT JOIN t_sales m ON m.uid = d.master_uid
        WHERE m.consumer_uid = m_consumers.uid
      ), 0)`), 'money'],
        [Sequelize.literal(`IFNULL((
        SELECT COUNT(*)
        FROM t_sales m
        WHERE m.consumer_uid = m_consumers.uid
      ), 0)`), 'times']]
      },
      where,
      order,
      offset: count ? startRow : undefined,
      limit: count || undefined,
      group: count ? `${modelName}.id` : undefined
    });
  } catch (e) {
    console.error(modelLabel + '列表出错', e);
  }

  // 处理其它数据
  const rows = [];
  ret.rows.forEach(row => {
    const jsonRow = row.toJSON();

    jsonRow._owner = row.create_user_id == user.id; // 是否为拥有者
    rows.push(jsonRow);
  });

  if (filter && filter.id) {
    return rows.length > 0 ? rows[0] : {};
  } else {
    res.json({
      data: rows,
      rowsNumber: typeof ret.count === 'object' ? ret.count.length : ret.count
    });
  }
};

// 详细信息
export const detail = async (req, res) => {
  req.body.filter = { id: req.body.id };

  const ret = await list(req);

  res.json(ret);
};

/**
 * 新增
 */
// export const create = async (req, res) => {
//   const { formData } = req.body;
//   const ret = await singleUtils.createData(modelName, modelLabel, menuName, req);

//   // 更新有效期
//   await models.m_tenants.update({
//     expire_time: formData.expire_time
//   }, {
//     where: {
//       id: formData.tenant_id
//     }
//   });

//   res.json(ret);
// };

/**
 * 更新
 */
export const update = async (req, res) => {
  const { id, formData } = req.body;
  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);

  const data = TableHelper.filterField(modelName, formData);

  try {
    const rawData = await models[modelName].findByPk(id);

    for (const key in data) {
      rawData[key] = data[key];
    }
    await rawData.save();
  } catch (e) {
    console.error('修改' + modelLabel + '出错', e);
  }

  logs.recordLogs(user, { type: 'edit', model: modelLabel, content: { formData } }, req);
  res.json({ result: 'ok' });
};

/**
 * 删除
 */
// export const destroy = async (req, res) => {
//   const ret = await singleUtils.destroyData(modelName, modelLabel, menuName, req);
//   res.json(ret);
// };

// 统计
export const summary = async (req, res) => {
  const { startRow, count, filter, sortBy, descending, columns } = req.body;

  const where = await tools.assemblyWhere({ filter, searchConfig: summaryConfig.search, raw: true });

  const user = await tools.getLoginUser(req.get('Authorization').split(' ')[1]);
  // const right = await tools.checkUserRight(user, menuName, ['data']);
  // if (!right.data) { // 是否有查看全部的权限
  //   where.push(`create_user_id=${user.id}`);
  // }

  const order = [];
  if (['year', 'month', 'day'].includes(sortBy)) { // 日期型的一起排序
    if (columns.includes('year')) {
      order.push(`year ${descending ? 'DESC' : 'ASC'}`);
    }
    if (columns.includes('month')) {
      order.push(`month ${descending ? 'DESC' : 'ASC'}`);
    }
    if (columns.includes('day')) {
      order.push(`day ${descending ? 'DESC' : 'ASC'}`);
    }
  } else {
    sortBy && columns.includes(sortBy) && order.push(`${sortBy} ${descending ? 'DESC' : 'ASC'}`);
  }

  const limit = count ? `LIMIT ${startRow}, ${count}` : '';

  // group by 字段
  const groupField = columns.filter(v => ['year', 'month', 'day', 'nickname', 'fullname'].includes(v)).join(', ');

  const allDataSql = `SELECT @idx:=@idx+1 AS id, ${groupField ? groupField + ',' : ''}
    COUNT(DISTINCT nickname) bill_count, SUM(IFNULL(money, 0)) money
    FROM (
      SELECT FROM_UNIXTIME(c.create_time, '%Y') year,
      FROM_UNIXTIME(c.create_time, '%m') month, FROM_UNIXTIME(c.create_time, '%d') day,
      c.nickname, c.fullname, d.money
      FROM m_consumers c
      LEFT JOIN t_sales m ON m.consumer_uid=c.uid
      LEFT JOIN t_sale_details d ON m.uid=d.master_uid
      ${where.length > 0 ? ' WHERE ' + where.join(' AND ') : ''}
    ) a, (SELECT @idx:=0) p
    GROUP BY ${groupField || ''}`;

  const [stat] = await mysql.query(`SELECT COUNT(*) cnt,
    IFNULL(SUM(bill_count), 0) bill_count,
    IFNULL(SUM(money), 0) money
    FROM (${allDataSql}) a`);

  let rows = [];
  const sql = `${allDataSql}
    ${order.length > 0 ? ' ORDER BY ' + order.join(',') : ''}
    ${limit}`;
  try {
    [rows] = await mysql.query(sql);
  } catch (e) {
    console.log(e, sql);
  }

  let bill_count = 0, money = 0;
  rows.forEach(row => {
    row.bill_count = Number(row.bill_count);
    row.money = Number(row.money);

    bill_count += row.bill_count;
    money += row.money;
  });

  res.json({
    data: rows,
    rowsNumber: stat[0].cnt,
    summary: {
      total: {
        bill_count: Number(stat[0].bill_count),
        money: Number(stat[0].money)
      },
      page: {
        bill_count,
        money
      }
    }
  });
};
